<?php

/**
 * importMedia actions.
 *
 * @package    LIAnnot
 * @subpackage importMedia
 * @author     Cedric Richier
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class importMediaActions extends sfActions
{
	/**
	 * Executes index action
	 *
	 * @param sfRequest $request A request object
	 */
	public function executeIndex(sfWebRequest $request)
	{
		if(!empty($_FILES['file']) && !empty($_POST["projectName"])) {
			$projectName = $_POST["projectName"];
					
			//	Check wether project with same name exists
			$listAnnoset = Doctrine::getTable("Annoset")
				->CreateQuery('a')->select()
				->execute();
			$found = false;
			foreach($listAnnoset as $annoset) {
				$name = $annoset->getName();
				$name = explode('.',$name);
				$name = $name[0];
				if($name == $projectName){
					$found = true;
					break;
				}
			}	
			$this->found = $found;			
			if(!$found) {
				$fileToUpload = new Fichier("file");
				//  si le fichier n'est pas trop volumineux
				if (!$fileToUpload->fichierVolumineux()) {
					$fileToUpload->tranfererFichier(sfConfig::get('sf_upload_dir').'/media_file.xml');
					$this->project_name = $this->importMedia($projectName);
				}
							
				if($this->project_name) {
					
					Paula::saveInBd($this->project_name , $this->getUser()->getUserName());
				}
			} else {
				 $this->getUser()->setFlash('error', "Project with name : '$projectName' already exists !");
			}
		}
		$this->redirect('main/projectList');
	}

	public function executeBuildProject(sfWebRequest $request)
	{

		//*/
	}



	private function initPaulaFile($project_name, $paula_name, $paula_type, $paula_base){

		if($paula_name == 'anno')
		$paula_name .= 'Set';

		if($paula_name == 'anno_feat')
		$paula_name = 'annoFeat';

		$imp = new DOMImplementation();
		$dtd = $imp->createDocumentType('paula', null, 'paula_'.$paula_type.'.dtd');
		$document = $imp->createDocument(null, 'paula', $dtd);
		$document->encoding = 'UTF-8';
		$document->formatOutput = true;

		$paula = $document->documentElement;
		$paula->setAttribute('version', '1.0');

		$paula_id = $project_name.'.'.$paula_name;
		$header = $document->createElement('header');
		$header->setAttribute('paula_id', $paula_id);
		$paula->appendChild($header);

		if($paula_type == 'text'){
			$header->setAttribute('type', $paula_type);
			$body = $document->createElement('body');
			$body->nodeValue = '';
			$paula->appendChild($body);
		}
		else{
			$list = $document->createElement($paula_type.'List');
			$list->setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink");

			if($paula_base)
			$list->setAttribute('xml:base',$project_name.'.'.$paula_base.'.xml');

			$list->setAttribute("type",$paula_name);
			$paula->appendChild($list);
		}

		return $document;
	}


	private function initPaulaDir($project_name){

		$paula_files = array();
		$keys = array('type', 'base');

		$paula_files_info['anno'] = array_combine($keys, array('struct', null));
		$paula_files_info['anno_feat'] = array_combine($keys, array('feat', 'anno'));
		$paula_files_info['text'] = array_combine($keys, array('text', null));
		$paula_files_info['tok'] = array_combine($keys, array('mark', 'text'));
		$paula_files_info['turn'] = array_combine($keys, array('mark', 'tok'));
		$paula_files_info['att'] = array_combine($keys, array('mark', 'tok'));
		$paula_files_info['att_feats'] = array_combine($keys, array('multiFeat', 'att'));
		$paula_files_info['frame'] = array_combine($keys, array('struct', null));
		$paula_files_info['frame_feats'] = array_combine($keys, array('multiFeat', 'frame'));
		$paula_files_info['frame_links_feats'] = array_combine($keys, array('feat', 'frame'));

		$paula_files = array();
		$paula_lastChilds = array();
		foreach($paula_files_info as $paula_name=>$paula_infos){
			$paula_files[$paula_name] = $this->initPaulaFile($project_name, $paula_name, $paula_infos['type'], $paula_infos['base']);
			$var_name = $paula_name.'_';

			if($paula_name == 'text')
			$var_name .= 'body';
			else
			$var_name .= $paula_infos['type'].'List';

			$paula_lastChilds[$var_name] = $paula_files[$paula_name]->documentElement->lastChild;
			//$paula_files[$paula_name]->save($project_name.'.'.$paula_name.'.xml');
		}

		return array_combine(array('files', 'last_childs'), array($paula_files, $paula_lastChilds));
	}


	private function idRewrite($id_old, $element_type, $prefix = true){

		$tmp = preg_split('/_/',$id_old);

		$id_new = '';
		for($i = 0; $i < count($tmp)-1; $i++){
			if($i == count($tmp)-2)
			$id_new .= $tmp[$i];
			else
			$id_new .= $tmp[$i].'_';
		}
			
		if($element_type == 'fe')
		$id_new = $this->idRewrite($id_new, 'frame', false);

		$id_new .= '_';

		$end_id = $tmp[count($tmp)-1];

		if($element_type == 'attvalue')
		$end_id = substr($end_id, 2);

		if($element_type == 'frame' || $element_type == 'fe')
		$end_id = substr($end_id, 1);

		if($end_id < 10)
		$end_id = '0'.$end_id;

		if($element_type == 'attvalue'){
			$end_id = '50'.$end_id;
			$element_type = 'att';
		}

		if($element_type == 'frame')
		$end_id = 'f'.$end_id;


		if($element_type == 'fe'){
			$end_id = 'e'.$end_id;
			$element_type = 'rel';
		}

		if($element_type == 'token')
		$element_type = 'tok';

		$id_new .= $end_id;
		if($prefix === true)
		$id_new = $element_type.'_'.$id_new;

		return $id_new;
	}


	private function hrefByType($type, $prefix){
		$href = '';
		switch($type){

			case 'token':
				$type = 'tok';
				break;

			case 'attvalue':
				$type = 'att';
				break;

			default :
				break;
		}
		if($type != 'frame')
		$href = $prefix.'.'.$type.'.xml';

		return $href;
	}


	private function importMedia($project = null){

		try{
		$file_name = 'uploads/media_file.xml';

		$doc = new DomDocument();
		if(!$doc->load($file_name)){
			throw new Exception();
		}//*/

		if(!$project){
			if(!$doc->getElementsByTagName('corpus'))
				throw new Exception();//*/
			$corpus_name = $doc->getElementsByTagName('corpus')->item(0)
					->getAttribute('corpusname');
		}
		else
		$corpus_name = $project;

		$dial_nbr = preg_split('/_/', $doc->getElementsByTagName('turn')->item(0)->getAttribute('id'));
		$dial_nbr = $dial_nbr[0];
		$project_name = $corpus_name.'.'.$dial_nbr;

		$return = $this->initPaulaDir($project_name);
		$paula_files = $return['files'];
		extract($return['last_childs']);
		unset($return);


		/*update anno.xml*/
		$keys = array();
		$file_by_keys = array();
		foreach($paula_files as $name=>$file){
			$key_name = preg_split('/_/', $name);
			$key_name = $key_name[0];
			if(!in_array($key_name, $keys)){
				array_push($keys, $key_name);
				$file_by_keys[$key_name]['files'] = array();
			}
			if($name != 'anno')
			array_push($file_by_keys[$key_name]['files'], $name);

			switch($key_name){
					
				case 'tok':
					$file_by_keys[$key_name]['bases'] = array('text');
					break;
						
				case 'turn':
					$file_by_keys[$key_name]['bases'] = array('tok');
					break;
						
				case 'att':
					$file_by_keys[$key_name]['bases'] = array('tok');
					break;
						
				case 'frame':
					$file_by_keys[$key_name]['bases'] = array('att', 'tok');
					break;
						
				default:
					$file_by_keys[$key_name]['bases'] = array(null);
					break;
			}
		}


		foreach($file_by_keys as $layer=>$file_names){
			$rel_cmpt = 1;
			$struct = $paula_files['anno']->createElement('struct');
			$anno_structList->appendChild($struct);
			if($layer == 'anno')
			$layer .= 'Set';

			$struct->setAttribute('id', 'layer_'.$layer);

			foreach($file_names['files'] as $file_name){
				$rel = $paula_files['anno']->createElement('rel');
				$struct->appendChild($rel);
				$rel->setAttribute('id', 'rel_layer_'.$layer.'_'.$rel_cmpt);
				$rel->setAttribute('xlink:href', $project_name.'.'.$file_name.'.xml');
					
				/*update anno_feat.xml*/
				$feat = $paula_files['anno_feat']->createElement('feat');
				$anno_feat_featList->appendChild($feat);
				$feat->setAttribute('xlink:href', '#rel_layer_'.$layer.'_'.$rel_cmpt);
				if($file_name== 'anno_feat')
				$file_name = 'annoFeat';
				$feat->setAttribute('value', $file_name);
				$rel_cmpt++;
			}

			foreach($file_names['bases'] as $base){
				if($base === null)
				continue;
				$rel = $paula_files['anno']->createElement('rel');
				$struct->appendChild($rel);
				$rel->setAttribute('id', 'rel_layer_'.$layer.'_'.$rel_cmpt);
				$rel->setAttribute('xlink:href', '#layer_'.$base);
					
				/*update anno_feat.xml*/
				$feat = $paula_files['anno_feat']->createElement('feat');
				$anno_feat_featList->appendChild($feat);
				$feat->setAttribute('xlink:href', '#rel_layer_'.$layer.'_'.$rel_cmpt);
				$feat->setAttribute('value', 'sub_layer_'.$base);
				$rel_cmpt++;
			}
		}

		unset($keys, $file_by_keys);

		$compt = 1;


		/*************************************/
		/*              turn                 */
		/*************************************/


		foreach($doc->getElementsByTagName('turn') as $turn){

			$turn_mark = $paula_files['turn']->createElement('mark');

			$turn_id = 'turn_'.$turn->getAttribute('id');
			$tokens = $turn->getElementsByTagName('token');

			$turn_mark->setAttribute('id', $turn_id);
			$turn_sons = array();


			/******************************************/
			/*			          token                   */
			/******************************************/

			foreach($tokens as $token){
					
				$token_id = $this->idRewrite($token->getAttribute('id'), 'token');

				if(!in_array($token_id,$turn_sons))
				array_push($turn_sons,$token_id);
				 
				/*update text.xml*/
				$text_body->nodeValue .= $token->nodeValue;

				/*update tok.xml*/
				$tok_mark = $paula_files['tok']->createElement('mark');
				$tok_mark->setAttribute('id',$token_id);

				$val = "#xpointer(string-range(//body,'',".$compt.",".mb_strlen($token->nodeValue, 'UTF-8')."))";
				$tok_mark->setAttribute('xlink:href',$val);
				$tok_markList->appendChild($tok_mark);

				$compt += mb_strlen($token->nodeValue, 'UTF-8');
			}

			/*update turn.xml*/
			$turn_mark->setAttribute('xlink:href',Paula::arrayToXlink($turn_sons));
			$turn_markList->appendChild($turn_mark);


			/************/
			/* attvalue */
			/************/

			foreach($turn->getElementsByTagName('attvalue') as $att){

				$att_mark = $paula_files['att']->createElement('mark');
				$att_markList->appendChild($att_mark);

				$att_id = $this->idRewrite($att->getAttribute('id'), 'attvalue');

				$att_mark->setAttribute('id',$att_id);

				$att_sons = array();
				foreach(preg_split('/ /',$att->getAttribute('span')) as $id){

					$tmp = preg_split('/_/',$id);
					$id = '';
					for($i= 0; $i< count($tmp)-1; $i++)
					$id = $id.$tmp[$i].'_';

					if((float)$tmp[count($tmp)-1] < 10)
					$id = $id.'0'.$tmp[count($tmp)-1];
					else
					$id = $id.$tmp[count($tmp)-1];
						
					$id = 'tok_'.$id;

					array_push($att_sons,$id);
				}

				$att_mark->setAttribute('xlink:href',Paula::arrayToXlink($att_sons));


				$att_feats_multiFeat = $paula_files['att_feats']->createElement('multiFeat');
				$att_feats_multiFeatList->appendChild($att_feats_multiFeat);
				$att_feats_multiFeat->setAttribute('xlink:href', '#'.$att_id);

				$att_attributes = array('cat', 'mode', 'specifier', 'value');
				foreach ($att_attributes as $attribute){
					$att_feats_feat = $paula_files['att_feats']->createElement('feat');
					$att_feats_multiFeat->appendChild($att_feats_feat);
					$value = $att->getAttribute($attribute);
					$att_feats_feat->setAttribute('name', $attribute);
					$att_feats_feat->setAttribute('value', $value);
				}
			}


			/**********************/
			/*       frame        */
			/**********************/

			foreach($turn->getElementsByTagName('frame') as $frame){
					
				$frame_id = $this->idRewrite($frame->getAttribute('id'), 'frame');

				/*update frame_feats.xml*/
				$frame_feats_multiFeat = $paula_files['frame_feats']->createElement('multiFeat');
				$frame_feats_multiFeatList->appendChild($frame_feats_multiFeat);
				$frame_feats_multiFeat->setAttribute('xlink:href', '#'.$frame_id);

				$frame_name = $frame->getAttribute('name');
				$frame_feats_feat = $paula_files['frame_feats']->createElement('feat');
				$frame_feats_multiFeat->appendChild($frame_feats_feat);
				$frame_feats_feat->setAttribute('name', 'name');
				$frame_feats_feat->setAttribute('value', $frame_name);

				/*update frame.xml*/
				$frame_struct = $paula_files['frame']->createElement('struct');
				$frame_structList->appendChild($frame_struct);
				$frame_struct->setAttribute('id',$frame_id);


				/*************************************/
				/*            target                 */
				/*************************************/

				$frame_target = $frame->getElementsByTagName('target')->item(0)->getElementsByTagName('fenode')->item(0);
				if($frame_target !== NULL) {
					$frame_target_type = $frame_target->getAttribute('type');
					$frame_target_id = $this->idRewrite($frame_target->getAttribute('idref'), $frame_target_type);

					$frame_struct_rel = $paula_files['frame']->createElement('rel');
					$frame_struct->appendChild($frame_struct_rel);
					$frame_struct_rel_id = 'rel'.str_replace('frame', '', $frame_id).'_target00';
					$frame_struct_rel->setAttribute('id', $frame_struct_rel_id);
					$href = $this->hrefByType($frame_target_type, $project_name);
					$frame_struct_rel->setAttribute('xlink:href', $href.'#'.$frame_target_id);
				}

				/*update frame_links_feats.xml*/
				$frame_links_feats_feat = $paula_files['frame_links_feats']->createElement('feat');
				$frame_links_feats_featList->appendChild($frame_links_feats_feat);
				$frame_links_feats_feat->setAttribute('xlink:href', '#'.$frame_struct_rel_id);
				$frame_links_feats_feat->setAttribute('value', 'target');


				/****************************/
				/*            fe            */
				/****************************/

				foreach($frame->getElementsByTagName('fe') as $fe){

					$fenode = $fe->getElementsByTagName('fenode')->item(0);
					$fenode_type = $fe->getElementsByTagName('fenode')->item(0)->getAttribute('type');
					$fenode_id = $this->idRewrite($fenode->getAttribute('idref'), $fenode_type);

					$fe_id = $this->idRewrite($fe->getAttribute('id'), 'fe');
					$fe_name = $fe->getAttribute('name');

					/*update frame.xml*/
					$rel = $paula_files['frame']->createElement('rel');
					$frame_struct->appendChild($rel);
					$rel->setAttribute('id', $fe_id);
					$href = $this->hrefByType($fenode_type, $project_name);
					$rel->setAttribute('xlink:href', $href.'#'.$fenode_id);

					/*update frame_links_feats.xml*/
					$feat = $paula_files['frame_links_feats']->createElement('feat');
					$frame_links_feats_featList->appendChild($feat);
					$feat->setAttribute('xlink:href', '#'.$fe_id);
					$feat->setAttribute('value', $fe_name);

				}
			}
		}
		$dir_path = 'uploads/projects/'.$project_name;
		mkdir($dir_path);
		Paula::copyDTD($dir_path);
		foreach($paula_files as $name=>$file)
		$file->save($dir_path.'/'.$project_name.'.'.$name.'.xml');
		} catch(Exception $e){
			$project_name = null;
		}//*/
		// delacement du fichier vers le repertoire du projet
		rename(sfConfig::get('sf_upload_dir').'/media_file.xml',sfConfig::get('sf_upload_dir').'/initMediaFiles/'.$project_name.'.xml');
		return $project_name;
	}

}
